// hooks
import { onBeforeRouteLeave } from 'vue-router'
import { useKeepPageStoreWithOut } from '@/store/modules/keepAlive'
const keepPageStore = useKeepPageStoreWithOut()
// 这里把targetPages参数设置为数组，因为目标页面可能有多个，比如B -> C, B -> D
export function useKeepPage(targetPages: string[] | 'all') {
  /**
   * @description: 设置页面缓存
   * @param {toName} string 目标页面name
   * @param {formName} string 来源页面name
   * @return {*}
   */
  const setKeepPage = (toName: string, formName: string) => {
    // 判断是否进入目标页面
    if (targetPages === 'all') {
      // 如果为 all 代表 则目标页面跳到到 任何页面再返回过来时都需要被缓存
      return keepPageStore.addIncludePage(formName)
    }
    if (!targetPages.includes(toName)) {
      // 当前页面不需要缓存目标页面，则就移除在 include 中移除目标页面
      keepPageStore.removeIncludePage(formName)
    } else {
      // 当前面需要缓存目标页面，则就在 include 中添加目标页面
      keepPageStore.addIncludePage(formName)
    }
  } // 在目标页面离开时触发

  onBeforeRouteLeave((to, form) => {
    setKeepPage(to.name as string, form.name as string)
  })
}
